package com.laowang.common.utils.gt;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

/**
 * @Auther laowang
 * @Date 2024/10/28
 * @Description
 */
public class RSAUtil {

    /**
     * 使用公钥对明文进行签名
     *
     * @param publicKey 公钥
     * @param plainText 明文
     * @return
     */
    public static String encrypt(String publicKey, String plainText) {
        try {
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, getPublicKey(publicKey));
            byte[] bytes = plainText.getBytes();
            ByteArrayInputStream read = new ByteArrayInputStream(bytes);
            ByteArrayOutputStream write = new ByteArrayOutputStream();
            byte[] buf = new byte[117];
            int len = 0;
            while ((len = read.read(buf)) != -1) {
                byte[] buf1 = null;
                if (buf.length == len) {
                    buf1 = buf;
                } else {
                    buf1 = new byte[len];
                    for (int i = 0; i < len; i++) {
                        buf1[i] = buf[i];
                    }
                }
                byte[] bytes1 = cipher.doFinal(buf1);
                write.write(bytes1);
            }
            return Base64Util.encode(write.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 得到公钥
     *
     * @param key 密钥字符串（经过base64编码�?
     * @throws Exception
     */
    public static PublicKey getPublicKey(String key) throws Exception {
        byte[] keyBytes;
        keyBytes = new BASE64Decoder().decodeBuffer(key);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        return publicKey;
    }


    /**
     * 生成公钥和私钥
     */
    public static void generateKey() {
        // 1.初始化秘钥
        KeyPairGenerator keyPairGenerator;
        try {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            SecureRandom sr = new SecureRandom(); // 随机数生成器
            keyPairGenerator.initialize(512, sr); // 设置512位长的秘钥
            KeyPair keyPair = keyPairGenerator.generateKeyPair(); // 开始创建
            RSAPublicKey rsaPublicKey = (RSAPublicKey) keyPair.getPublic();
            RSAPrivateKey rsaPrivateKey = (RSAPrivateKey) keyPair.getPrivate();
            // 进行转码
            String publicKey = Base64.encodeBase64String(rsaPublicKey.getEncoded());
            System.out.println("公钥："+ publicKey);
            // 进行转码
            String privateKey = Base64.encodeBase64String(rsaPrivateKey.getEncoded());
            System.out.println("私钥："+privateKey);
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        RSAUtil.generateKey();
        //公钥：MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAOifBXCtMgzb3c8WqbZ9DHq7beZVFIEQyLgmanYG4CxK0r4NcFm6IOGbb6EE+OlwF49d5AeVffCvF9nnMojrPcsCAwEAAQ==
        //私钥：MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA6J8FcK0yDNvdzxaptn0Mertt5lUUgRDIuCZqdgbgLErSvg1wWbog4ZtvoQT46XAXj13kB5V98K8X2ecyiOs9ywIDAQABAkAM9Yb1DwEBzGHf/pA31WGTmMt3kHfS9N9puuIlbx6f+PPxjcNydTPdVmdq+BDRvjo/oWib7IB473OmyTL5tECZAiEA9s6ZomZv6bWXioC0OuZXlqIBsWRSPy1NKBpWZgfrCI0CIQDxSSdOUgsoMvAjkzRcADe05PhVUp6Usmtce/uI6srltwIhAMe6sgIGvBJ57kUbmr7/oWo5eP1Bnn2Z/5KwnbK8PawRAiEAk5kmXDi/7nVKhNiVnPndGeE/MCJ8M4X5Ovf05MqMF30CIC35kj7CmmydvwoP+eXDN6wwcVlgOoZzsEVX8zvKDhuF
    }
}
